# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
from collections import OrderedDict
from datetime import datetime
import sys
import pdfkit
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.template import RequestContext
from django.template.loader import get_template
from django.views.decorators.cache import never_cache

from wlapps.utils.base62 import wldecode
from wlmodels.codes.models import ELHGGoodsCode
from wlmodels.company.models import ELPost, ELManager, ELInv, ELCaseDetail, ELCasePunish, ELMortReg, \
    ELMortGua, ELMortClaim, ELStockFrost, ELStockImpawn, ELNameHistory, ELCredit
from wlmodels.companyplus.models import ELFinanceTax, ELFinanceIndex, ELHGEnt, ELHGEntDetail, ELHGEntGoods
from wlmodels.dataplus.models import ELPatentEnt, ELStatisticsCredit, ELCopyrightSoftware, ELCopyrightProduction, \
    ELTminfo
from wlviews.saas.fee import customer_verify_fee, noauth_redirct_url

from wlviews.apis.apis import FBAPI, WmyAPI
from wlviews.apis.utils import news_filter
from wlviews.report.powerModel import getJsonData, add_power_score
from wlviews.report.power_demo import getJsonDetail

reload(sys)
sys.setdefaultencoding('utf8')


# from .tupu import tupu_create_echarts_xml, edge_distinct, gen_touzi_edgetext



def get_index_from_data_engine(id):
    return random.uniform(0, 72)


@never_cache
def gen_pdf(request, entid=None):
    entid = wldecode(entid, addcrc=True)
    if not entid or entid > 500000000:
        raise Http404
    el_post = get_object_or_404(ELPost, entid=entid)
    company_obj = ELPost.objects.filter(entid=entid).first()
    version = request.GET.get("version", None)  # 报告版本，10全景，11标准
    if version not in ["10", "11"]:
        version = "10"
    version_dict = {"10": "全景版", "11": "标准版"}
    context = {"el_post": el_post, "version": version, }
    # 先进行计费
    # if customer_verify_fee(request, saas_pindao="20", saas_item=version, tkey=ent id):
    #     return HttpResponseRedirect(noauth_redirct_url)
    #     # 加载信用评分
    year_list = [2016, 2015, 2014, 2013, 2012]
    the_credit = {"total": [], "detail": []}
    context["latest_year"] = 2012
    for tyear in year_list:
        sr_obj = ELStatisticsCredit.objects.filter(year=tyear, region_name__isnull=False)
        sn_obj = ELStatisticsCredit.objects.filter(year=tyear, nic_name__isnull=False)
        credit_obj = ELCredit.objects.filter(entid_id=entid, year=tyear).first()
        if credit_obj:
            index_total = credit_obj.index_total if credit_obj.index_total else 360 + int(sum(
                [credit_obj.index_3_1 * 0.05, credit_obj.index_3_2 * 0.05, credit_obj.index_3_3 * 0.05,
                 credit_obj.index_3_4 * 0.05,
                 credit_obj.index_3_5 * 0.05, credit_obj.index_3_6 * 0.05, credit_obj.index_3_7 * 0.05,
                 credit_obj.index_3_8 * 0.05,
                 credit_obj.index_3_9 * 0.12, credit_obj.index_3_10 * 0.12,
                 credit_obj.index_3_11 * 0.2, credit_obj.index_3_12 * 0.15]))
            credit_obj = add_power_score(credit_obj, company_obj.ENTNAME, tyear + 1)
            index_total = credit_obj.index_total
            the_credit["total"].append({"year": tyear + 1, "value": index_total})
            the_credit["detail"].append(
                {"year": tyear + 1, "value": credit_obj, "statistic_r": sr_obj, "statistic_n": sn_obj})
            if (tyear + 1) > context["latest_year"]:
                context["latest_year"] = tyear + 1
    # 如果暂无该企业的任何评分，则展示默认数据
    if len(the_credit["total"]) == 0:
        sr_obj = ELStatisticsCredit.objects.filter(year=2014, region_name__isnull=False)
        sn_obj = ELStatisticsCredit.objects.filter(year=2014, nic_name__isnull=False)
        tmp_obj = ELCredit()
        tmp_obj.index_2_1 = 36
        tmp_obj.index_2_2 = 36
        tmp_obj.index_2_3 = 36
        tmp_obj.index_2_4 = 36
        tmp_obj.index_2_5 = 36
        tmp_obj.index_3_1 = 36
        tmp_obj.index_3_2 = 36
        tmp_obj.index_3_3 = 36
        tmp_obj.index_3_4 = 36
        tmp_obj.index_3_5 = 36
        tmp_obj.index_3_6 = 36
        tmp_obj.index_3_7 = 36
        tmp_obj.index_3_8 = 36
        tmp_obj.index_3_9 = 36
        tmp_obj.index_3_10 = 36
        tmp_obj.index_3_11 = 36
        tmp_obj.index_3_12 = 36
        tmp_obj.index_3_13 = 36
        the_credit = {"total": [{"year": 2015, "value": 360}],
                      "detail": [{"year": 2015, "value": tmp_obj, "statistic_r": sr_obj, "statistic_n": sn_obj}]}
        context["latest_year"] = 2015
    context["credit"] = the_credit

    # 取得报告信息
    # 工商基础
    el_name_history = ELNameHistory.objects.filter(entid_id=entid).values_list("ENTNAME", flat=True)
    if len(el_name_history):
        context["el_name_history"] = ", ".join(el_name_history)
    context["el_managers"] = el_post.c_manager.all()
    context["el_invs"] = el_post.c_inv.all()
    context["el_modifys"] = el_post.c_modify.all()
    the_cancel = el_post.c_cancel.all().first()
    if the_cancel:
        context["el_cancel"] = the_cancel
    the_revoke = el_post.c_revoke.all().first()
    if the_revoke:
        context["el_revoke"] = the_revoke

        # 关联幕后
    # 企业对外投资
    context["el_entinvs"] = ELInv.objects.filter(entid_inv=entid)
    # 法人id
    fr_personid, other_personids = ELPost.get_person_ids(entid)
    # 法人对外投资和任职
    if fr_personid:
        context["el_frinvs"] = ELInv.objects.filter(personid=fr_personid).exclude(entobj=entid)
        context["el_frpositions"] = ELManager.objects.filter(personid=fr_personid).exclude(entobj=entid)
    # 股东高管对外投资和任职
    if len(other_personids) and version in ["10", ]:
        context["el_personinvs"] = ELInv.objects.filter(personid__in=other_personids).exclude(entobj=entid)
        context["el_personpositions"] = ELManager.objects.filter(personid__in=other_personids).exclude(entobj=entid)
    # 分支机构
    context["el_filiations"] = el_post.c_filiation.all()

    # 财务分析所需json
    if version in ["10", ]:
        caiwudata = {"finance": {}, "financeRate": {}, "customs": {"1": {}, "2": {}},
                     "goods": {2014: {}, 2015: {}, 2016: {}}}
        for year in [2012, 2013, 2014, 2015]:
            tax_year = ELFinanceTax.objects.filter(entid_id=entid, year=year).first()
            if tax_year:
                caiwudata["finance"][str(year)] = {"revenue": tax_year.revenue,
                                                   "sales_cost": tax_year.sales_cost if tax_year.sales_cost else "",
                                                   "sales_tax": tax_year.sales_tax if tax_year.sales_tax else "",
                                                   "sales_expense": tax_year.sales_expense if tax_year.sales_expense else "",
                                                   "G_expense": tax_year.G_expense if tax_year.G_expense else "",
                                                   "finance_expense": tax_year.finance_expense if tax_year.finance_expense else "",
                                                   "asset_devaluation_losses": tax_year.asset_devaluation_losses if tax_year.asset_devaluation_losses else "",
                                                   "fair_value_change": tax_year.fair_value_change if tax_year.fair_value_change else "",
                                                   "investment_income": tax_year.investment_income if tax_year.investment_income else "",
                                                   "operation_profit": tax_year.operation_profit if tax_year.operation_profit else "",
                                                   "non_operating_income": tax_year.non_operating_income if tax_year.non_operating_income else "",
                                                   "non_operating_expense": tax_year.non_operating_expense if tax_year.non_operating_expense else "",
                                                   "total_profit": tax_year.total_profit if tax_year.total_profit else "",
                                                   "assets_re": tax_year.assets_re if tax_year.assets_re else "",
                                                   "incometax_actual": tax_year.incometax_actual if tax_year.incometax_actual else "", }
            else:
                caiwudata["finance"][str(year)] = {"revenue": "", "sales_cost": "", "sales_tax": "",
                                                   "sales_expense": "", "G_expense": "",
                                                   "finance_expense": "", "asset_devaluation_losses": "",
                                                   "fair_value_change": "",
                                                   "investment_income": "", "operation_profit": "",
                                                   "non_operating_income": "",
                                                   "non_operating_expense": "", "total_profit": "", "assets_re": "",
                                                   "incometax_actual": "", }
            tax_index = ELFinanceIndex.objects.filter(entid_id=entid, year=year).first()
            if tax_index:
                caiwudata["financeRate"][str(year)] = {"gross": tax_index.gross if tax_index.gross else "",
                                                       "profit": tax_index.profit if tax_index.profit else "",
                                                       "profit_net": tax_index.profit_net if tax_index.profit_net else "",
                                                       "asset_return": tax_index.asset_return if tax_index.asset_return else "",
                                                       "income_increase": tax_index.income_increase if tax_index.income_increase else "",
                                                       "profit_increase": tax_index.profit_increase if tax_index.profit_increase else "",
                                                       "profit_net_increase": tax_index.profit_net_increase if tax_index.profit_net_increase else ""}
            else:
                caiwudata["financeRate"][str(year)] = {"gross": "", "profit": "", "profit_net": "", "asset_return": "",
                                                       "income_increase": "",
                                                       "profit_increase": "", "profit_net_increase": ""}
        # 海关企业月度详情
        hg_objs = ELHGEnt.objects.filter(entid_id=entid)
        if len(hg_objs):
            caiwudata["customs"]['1'] = OrderedDict()
            caiwudata["customs"]['2'] = OrderedDict()
            for tmonth in [1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1501, 1502, 1503,
                           1504, 1505, 1506, 1507, 1508,
                           1509, 1510, 1511, 1512, 1601, 1602, 1603, 1604, 1605, 1606, 1607, 1608]:
                for tport in ["1", "2"]:
                    tax_hg = ELHGEntDetail.objects.filter(entid_id=entid, tmonth=tmonth, tport=tport).first()
                    if tax_hg:
                        caiwudata["customs"][tport][str(tmonth)] = tax_hg.scale if tax_hg.scale else ""
                    else:
                        caiwudata["customs"][tport][str(tmonth)] = ""
        else:
            caiwudata["customs"] = ""
        # 企业商品年度分类统计
        hg_goods = ELHGEntGoods.objects.filter(entid_id=entid)
        for hg_good in hg_goods:
            if hg_good.statics:
                goods_statics = json.loads(hg_good.statics)
                for key in goods_statics.keys():
                    good_name = ELHGGoodsCode.objects.filter(code=key).first()
                    if good_name:
                        goods_statics[good_name.name] = goods_statics[key]
                        del goods_statics[key]
                caiwudata["goods"][hg_good.tyear] = goods_statics
        context["caiwudata"] = json.dumps(caiwudata)

    # 风险失信
    context["el_stockfrosts"] = ELStockFrost.objects.filter(entid_id=entid)
    context["el_stockimpawns"] = ELStockImpawn.objects.filter(entid_id=entid)
    context["el_liquidations"] = el_post.c_liquidation.all()
    context["case_basic"] = []
    case_basics = el_post.case_basic.all()
    for case in case_basics:
        the_detail = ELCaseDetail.objects.filter(caseid=case.caseid).first()
        if the_detail:
            case.CASETIME = the_detail.CASETIME
            case.CASEREASON = the_detail.CASEREASON
            case.CASEVAL = the_detail.CASEVAL
            case.EXESORT = the_detail.get_EXESORT_display()
            case.CASERESULT = the_detail.get_CASERESULT_display()
        the_punish = ELCasePunish.objects.filter(caseid=case.caseid).first()
        if the_punish:
            case.ILLEGACTTYPE = the_punish.ILLEGACTTYPE
            case.PENDECISSDATE = the_punish.PENDECISSDATE
            case.PENAUTH = the_punish.PENAUTH
            case.PENDECNO = the_punish.PENDECNO
            case.ILLEGFACT = the_punish.ILLEGFACT
            case.PENBASIS = the_punish.PENBASIS
            case.PENTYPE = the_punish.get_PENTYPE_display()
            case.PENRESULT = the_punish.get_PENRESULT_display()
            case.PENAM = the_punish.PENAM
            case.PENEXEST = the_punish.PENEXEST
        if the_detail or the_punish:
            context["case_basic"].append(case)

    # 资产交易
    if version in ["10", ]:
        mort_objs = ELMortReg.objects.filter(entid_id=entid)
        if mort_objs.count():
            context["el_mort_guas"] = ELMortGua.objects.filter(MORREG_ID__in=[x.MORREG_ID for x in mort_objs])
        else:
            context["el_mort_guas"] = []
        for mort_obj in mort_objs:
            the_claim = mort_obj.mort_claim.all().first()
            if the_claim:
                mort_obj.the_claim = the_claim
            else:
                mort_obj.the_claim = ELMortClaim()
        context["el_morts"] = mort_objs
        context["el_patents"] = ELPatentEnt.objects.filter(entid_id=entid)
        # 土地信息
        context["land_objs"] = []
        if len(el_post.REGNO) > 7:
            land_dict = FBAPI(el_post.REGNO).get_land()
            if "total" in land_dict and "hits" in land_dict:
                context["land_total"] = land_dict["total"]
                land_objs = []
                key_dict = {"公告类别": "gglb", "公示期": "gsq", "出让年限": "crnx", "单位地址": "dwdz", "受让单位": "srdw",
                            "土地用途": "tdyt", "土地面积(公顷)": "tdmj",
                            "地块位置": "dkwz", "备注": "bz", "宗地编号": "zdbh", "成交价格(万元)": "cjjg", "标题": "title",
                            "电子邮件": "email", "联系人": "lxr",
                            "联系单位": "lxdw", "联系电话": "lxdh", "行政区": "qjx", "邮政编码": "postcode", }
                for tmp in land_dict["hits"]:
                    new_obj = {"gglb": "", "gsq": "", "crnx": "", "dwdz": "", "srdw": "", "tdyt": "", "tdmj": "",
                               "dkwz": "", "bz": "",
                               "zdbh": "", "cjjg": "", "title": "", "email": "", "lxr": "", "lxdw": "", "lxdh": "",
                               "qjx": "", "postcode": "", }
                    for key in key_dict.keys():
                        if key in tmp:
                            new_obj[key_dict[key]] = tmp[key]
                    land_objs.append(new_obj)
                context["land_objs"] = land_objs
        # 著作权
        context["zzq_objs"] = []
        if len(el_post.REGNO) > 7:
            zzq_dict = FBAPI(el_post.REGNO).get_zzq()
            if "total" in zzq_dict and "hits" in zzq_dict:
                context["zzq_total"] = zzq_dict["total"]
                zzq_objs = []
                key_dict = {'作品名称': 'zpmc', '首次发表日期': 'fbrq', '著作权人': 'zzqr', '软件简称': 'rjjc', '版本号': 'bbh',
                            '登记日期': 'djrq', '分类号': 'flh',
                            '公告日期': 'ggrq', '登记号': 'djh', '公告类型': 'gglx', '软件全称': 'rjqc', }
                for tmp in zzq_dict["hits"]:
                    new_obj = {'zpmc': '', 'fbrq': '', 'zzqr': '', 'rjjc': '', 'bbh': '', 'djrq': '', 'flh': '',
                               'ggrq': '', 'djh': '', 'gglx': '',
                               'rjqc': '', }
                    for key in key_dict.keys():
                        if key in tmp:
                            new_obj[key_dict[key]] = tmp[key]
                    zzq_objs.append(new_obj)
                context["zzq_objs"] = zzq_objs
        # ICP备案
        context["icp_objs"] = []
        if len(el_post.REGNO) > 7:
            icp_dict = FBAPI(el_post.REGNO).get_icp()
            if "total" in icp_dict and "hits" in icp_dict:
                context["icp_total"] = icp_dict["total"]
                icp_objs = []
                key_dict = {"主办单位名称": "zbdw", "主办单位性质": "dwxz", "审核通过时间": "tgsj", "网站名称": "wzmc", "网站域名": "host",
                            "网站备案/许可证号": "bah", }
                for tmp in icp_dict["hits"]:
                    if "网站域名" in tmp and isinstance(tmp["网站域名"], list):
                        tmp["网站域名"] = ";".join(tmp["网站域名"])
                        new_obj = {"zbdw": "", "dwxz": "", "tgsj": "", "wzmc": "", "host": "", "bah": "", }
                        for key in key_dict.keys():
                            if key in tmp:
                                new_obj[key_dict[key]] = tmp[key]
                        icp_objs.append(new_obj)
                context["icp_objs"] = icp_objs

    # 事件舆情
    if version in ["10", ]:
        context["news_objs"] = []
        if len(el_post.REGNO) > 7:
            news_dict = FBAPI(el_post.REGNO).get_news()
            if "event" in news_dict and "total" in news_dict["event"] and "hits" in news_dict["event"]:
                news_dict = news_filter(news_dict)
                context["news_objs"] = news_dict["event"]["hits"]

    # 招标招聘
    if version in ["10", ]:
        context["ztb_objs"] = []
        if len(el_post.REGNO) > 7:
            ztb_dict = FBAPI(el_post.REGNO).get_bid()
            if "total" in ztb_dict and "hits" in ztb_dict:
                ztb_objs = []
                key_dict = {"发布时间": "fbsj", "公告类型": "gglx", "地区": "dq", "标题": "bt", "正文": "zw", "采购人": "cgr",
                            "采购品目": "cgpm", "代理机构": "dljg"}
                for tmp in ztb_dict["hits"]:
                    new_obj = {"fbsj": "", "gglx": "", "dq": "", "bt": "", "zw": "", "cgr": "", "cgpm": "", "dljg": ""}
                    for key in key_dict.keys():
                        if key in tmp:
                            new_obj[key_dict[key]] = tmp[key]
                            ztb_objs.append(new_obj)
                context["ztb_objs"] = ztb_objs
        zp_objs = WmyAPI(el_post.ENTNAME).get_zp()
        for tmp in zp_objs:
            for ky in ["job_name", "posttime", "location", "education_requirement", "experience_requirement",
                       "salary_range", "url"]:
                if ky not in tmp:
                    tmp[ky] = ""
        context["zp_objs"] = zp_objs

    # 电力模型数据
    if version in ["10", ]:
        try:
            electricity_data = getJsonData(company_obj.ENTNAME)
            if electricity_data is None or electricity_data == "":
                electricity_data = getJsonDetail()
        except TypeError as e:
            electricity_data = getJsonDetail()
        # electricity_data = getJsonDetail()
        context['data'] = electricity_data

    # 渲染模版
    context['today'] = datetime.today()
    t1 = get_template("element/reportpdf/index.html")
    context['path'] = 'http://' + request.get_host()
    c = RequestContext(request, context)
    html = t1.render(c)

    options = {
        'margin-right': '0',
        'margin-left': '0',
        'encoding': "UTF-8",
        'header-spacing': 20,
        'header-html': 'templates/element/reportpdf/header.html',
        'footer-center': "--  [page]  --",
        'margin-bottom': '10',
        'footer-spacing': 1,
        'footer-font-size': 12,
        'footer-html': 'templates/element/reportpdf/footer.html',
        'javascript-delay': 700,
        'page-offset': -1,
        'outline-depth': 2
    }
    cover = 'http://' + request.get_host() + request.path + 'cover/?version=%s' % version
    toc = {
        'xsl-style-sheet': 'static/element/reportpdf/toc.xml'
    }

    # 创建内容页
    pdf = pdfkit.from_string(str(html.encode('utf-8')).decode('utf-8'), False, options=options, toc=toc, cover=cover,
                             cover_first=True)

    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = (
        'filename=%s-征信企业报告(%s).pdf' % (el_post.ENTNAME, version_dict[version])).encode("utf-8")
    response.write(pdf)
    return response


@never_cache
def pdf_cover(request, entid=None):
    entid = wldecode(entid, addcrc=True)
    if not entid or entid > 500000000:
        raise Http404
    el_post = get_object_or_404(ELPost, entid=entid)
    context = {"el_post": el_post, }
    context['path'] = 'http://' + request.get_host()
    context['today'] = datetime.today()
    context['version'] = request.GET['version'] or '11'
    return render(request, "element/reportpdf/cover.html", context)


@never_cache
def gen_pdf_for_java(request, raw_entid=None):
    entid = wldecode(raw_entid, addcrc=True)
    if not entid or entid > 500000000:
        raise Http404
    el_post = get_object_or_404(ELPost, entid=entid)
    company_obj = ELPost.objects.filter(entid=entid).first()
    version = request.GET.get("version", None)  # 报告版本，10全景，11标准
    if version not in ["10", "11"]:
        version = "10"
    version_dict = {"10": "全景版", "11": "标准版"}
    context = {"el_post": el_post, "version": version, }

    year_list = [2016, 2015, 2014, 2013]
    the_credit = {"total": [], "detail": []}
    context["latest_year"] = 2012
    for tyear in year_list:
        sr_obj = ELStatisticsCredit.objects.filter(year=tyear, region_name__isnull=False)
        sn_obj = ELStatisticsCredit.objects.filter(year=tyear, nic_name__isnull=False)
        credit_obj = ELCredit.objects.filter(entid_id=entid, year=tyear).first()
        if credit_obj:
            index_total = credit_obj.index_total if credit_obj.index_total else 360 + int(sum(
                [credit_obj.index_3_1 * 0.05, credit_obj.index_3_2 * 0.05, credit_obj.index_3_3 * 0.05,
                 credit_obj.index_3_4 * 0.05,
                 credit_obj.index_3_5 * 0.05, credit_obj.index_3_6 * 0.05, credit_obj.index_3_7 * 0.05,
                 credit_obj.index_3_8 * 0.05,
                 credit_obj.index_3_9 * 0.12, credit_obj.index_3_10 * 0.12,
                 credit_obj.index_3_11 * 0.2, credit_obj.index_3_12 * 0.15]))
            credit_obj = add_power_score(credit_obj, company_obj.ENTNAME, tyear + 1)
            index_total = credit_obj.index_total
            the_credit["total"].append({"year": tyear + 1, "value": index_total})
            the_credit["detail"].append(
                {"year": tyear + 1, "value": credit_obj, "statistic_r": sr_obj, "statistic_n": sn_obj})
            if (tyear + 1) > context["latest_year"]:
                context["latest_year"] = tyear + 1
        else:
            tmp_obj = ELCredit()
            tmp_obj.entid_id = entid
            tmp_obj.year = tyear
            tmp_obj.index_2_1 = get_index_from_data_engine(21)
            tmp_obj.index_2_2 = get_index_from_data_engine(22)
            tmp_obj.index_2_3 = get_index_from_data_engine(23)
            tmp_obj.index_2_4 = get_index_from_data_engine(24)
            tmp_obj.index_2_5 = get_index_from_data_engine(25)
            tmp_obj.index_3_1 = get_index_from_data_engine(31)
            tmp_obj.index_3_2 = get_index_from_data_engine(32)
            tmp_obj.index_3_3 = get_index_from_data_engine(33)
            tmp_obj.index_3_4 = get_index_from_data_engine(34)
            tmp_obj.index_3_5 = get_index_from_data_engine(35)
            tmp_obj.index_3_6 = get_index_from_data_engine(36)
            tmp_obj.index_3_7 = get_index_from_data_engine(37)
            tmp_obj.index_3_8 = get_index_from_data_engine(38)
            tmp_obj.index_3_9 = get_index_from_data_engine(39)
            tmp_obj.index_3_10 = get_index_from_data_engine(310)
            tmp_obj.index_3_11 = get_index_from_data_engine(311)
            tmp_obj.index_3_12 = get_index_from_data_engine(312)
            tmp_obj.index_total = 360 + int(sum(
                [tmp_obj.index_3_1 * 0.05, tmp_obj.index_3_2 * 0.05, tmp_obj.index_3_3 * 0.05,
                 tmp_obj.index_3_4 * 0.05,
                 tmp_obj.index_3_5 * 0.05, tmp_obj.index_3_6 * 0.05, tmp_obj.index_3_7 * 0.05,
                 tmp_obj.index_3_8 * 0.05,
                 tmp_obj.index_3_9 * 0.12, tmp_obj.index_3_10 * 0.12,
                 tmp_obj.index_3_11 * 0.2, tmp_obj.index_3_12 * 0.15]))
            tmp_obj.save()
            tmp_obj = add_power_score(credit_obj, company_obj.ENTNAME, tyear + 1)
            the_credit["total"].append({"year": tyear + 1, "value": tmp_obj.index_total})
            the_credit["detail"].append(
                {"year": tyear + 1, "value": tmp_obj, "statistic_r": sr_obj, "statistic_n": sn_obj})
            if (tyear + 1) > context["latest_year"]:
                context["latest_year"] = tyear + 1
    context["credit"] = the_credit

    # 取得报告信息
    # 工商基础
    el_name_history = ELNameHistory.objects.filter(entid_id=entid).values_list("ENTNAME", flat=True)
    if len(el_name_history):
        context["el_name_history"] = ", ".join(el_name_history)
    context["el_managers"] = el_post.c_manager.all()
    context["el_invs"] = el_post.c_inv.all()
    context["el_modifys"] = el_post.c_modify.all()
    the_cancel = el_post.c_cancel.all().first()
    if the_cancel:
        context["el_cancel"] = the_cancel
    the_revoke = el_post.c_revoke.all().first()
    if the_revoke:
        context["el_revoke"] = the_revoke

        # 关联幕后
    # 企业对外投资
    context["el_entinvs"] = ELInv.objects.filter(entid_inv=entid)
    # 法人id
    fr_personid, other_personids = ELPost.get_person_ids(entid)
    # 法人对外投资和任职
    if fr_personid:
        context["el_frinvs"] = ELInv.objects.filter(personid=fr_personid).exclude(entobj=entid)
        context["el_frpositions"] = ELManager.objects.filter(personid=fr_personid).exclude(entobj=entid)
    # 股东高管对外投资和任职
    if len(other_personids) and version in ["10", ]:
        context["el_personinvs"] = ELInv.objects.filter(personid__in=other_personids).exclude(entobj=entid)
        context["el_personpositions"] = ELManager.objects.filter(personid__in=other_personids).exclude(entobj=entid)
    # 分支机构
    context["el_filiations"] = el_post.c_filiation.all()

    # 财务分析所需json
    if version in ["10", ]:
        caiwudata = {"finance": {}, "financeRate": {}, "customs": {"1": {}, "2": {}},
                     "goods": {2014: {}, 2015: {}, 2016: {}}}
        for year in [2012, 2013, 2014, 2015]:
            tax_year = ELFinanceTax.objects.filter(entid_id=entid, year=year).first()
            if tax_year:
                caiwudata["finance"][str(year)] = {"revenue": tax_year.revenue,
                                                   "sales_cost": tax_year.sales_cost if tax_year.sales_cost else "",
                                                   "sales_tax": tax_year.sales_tax if tax_year.sales_tax else "",
                                                   "sales_expense": tax_year.sales_expense if tax_year.sales_expense else "",
                                                   "G_expense": tax_year.G_expense if tax_year.G_expense else "",
                                                   "finance_expense": tax_year.finance_expense if tax_year.finance_expense else "",
                                                   "asset_devaluation_losses": tax_year.asset_devaluation_losses if tax_year.asset_devaluation_losses else "",
                                                   "fair_value_change": tax_year.fair_value_change if tax_year.fair_value_change else "",
                                                   "investment_income": tax_year.investment_income if tax_year.investment_income else "",
                                                   "operation_profit": tax_year.operation_profit if tax_year.operation_profit else "",
                                                   "non_operating_income": tax_year.non_operating_income if tax_year.non_operating_income else "",
                                                   "non_operating_expense": tax_year.non_operating_expense if tax_year.non_operating_expense else "",
                                                   "total_profit": tax_year.total_profit if tax_year.total_profit else "",
                                                   "assets_re": tax_year.assets_re if tax_year.assets_re else "",
                                                   "incometax_actual": tax_year.incometax_actual if tax_year.incometax_actual else "", }
            else:
                caiwudata["finance"][str(year)] = {"revenue": "", "sales_cost": "", "sales_tax": "",
                                                   "sales_expense": "", "G_expense": "",
                                                   "finance_expense": "", "asset_devaluation_losses": "",
                                                   "fair_value_change": "",
                                                   "investment_income": "", "operation_profit": "",
                                                   "non_operating_income": "",
                                                   "non_operating_expense": "", "total_profit": "", "assets_re": "",
                                                   "incometax_actual": "", }
            tax_index = ELFinanceIndex.objects.filter(entid_id=entid, year=year).first()
            if tax_index:
                caiwudata["financeRate"][str(year)] = {"gross": tax_index.gross if tax_index.gross else "",
                                                       "profit": tax_index.profit if tax_index.profit else "",
                                                       "profit_net": tax_index.profit_net if tax_index.profit_net else "",
                                                       "asset_return": tax_index.asset_return if tax_index.asset_return else "",
                                                       "income_increase": tax_index.income_increase if tax_index.income_increase else "",
                                                       "profit_increase": tax_index.profit_increase if tax_index.profit_increase else "",
                                                       "profit_net_increase": tax_index.profit_net_increase if tax_index.profit_net_increase else ""}
            else:
                caiwudata["financeRate"][str(year)] = {"gross": "", "profit": "", "profit_net": "", "asset_return": "",
                                                       "income_increase": "",
                                                       "profit_increase": "", "profit_net_increase": ""}
        # 海关企业月度详情
        hg_objs = ELHGEnt.objects.filter(entid_id=entid)
        if len(hg_objs):
            caiwudata["customs"]['1'] = OrderedDict()
            caiwudata["customs"]['2'] = OrderedDict()
            for tmonth in [1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1501, 1502, 1503,
                           1504, 1505, 1506, 1507, 1508,
                           1509, 1510, 1511, 1512, 1601, 1602, 1603, 1604, 1605, 1606, 1607, 1608]:
                for tport in ["1", "2"]:
                    tax_hg = ELHGEntDetail.objects.filter(entid_id=entid, tmonth=tmonth, tport=tport).first()
                    if tax_hg:
                        caiwudata["customs"][tport][str(tmonth)] = tax_hg.scale if tax_hg.scale else ""
                    else:
                        caiwudata["customs"][tport][str(tmonth)] = ""
        else:
            caiwudata["customs"] = ""
        # 企业商品年度分类统计
        hg_goods = ELHGEntGoods.objects.filter(entid_id=entid)
        for hg_good in hg_goods:
            if hg_good.statics:
                goods_statics = json.loads(hg_good.statics)
                for key in goods_statics.keys():
                    good_name = ELHGGoodsCode.objects.filter(code=key).first()
                    if good_name:
                        goods_statics[good_name.name] = goods_statics[key]
                        del goods_statics[key]
                caiwudata["goods"][hg_good.tyear] = goods_statics
        context["caiwudata"] = json.dumps(caiwudata)

    # 风险失信
    context["el_stockfrosts"] = ELStockFrost.objects.filter(entid_id=entid)
    context["el_stockimpawns"] = ELStockImpawn.objects.filter(entid_id=entid)
    context["el_liquidations"] = el_post.c_liquidation.all()
    context["case_basic"] = []
    case_basics = el_post.case_basic.all()
    for case in case_basics:
        the_detail = ELCaseDetail.objects.filter(caseid=case.caseid).first()
        if the_detail:
            case.CASETIME = the_detail.CASETIME
            case.CASEREASON = the_detail.CASEREASON
            case.CASEVAL = the_detail.CASEVAL
            case.EXESORT = the_detail.get_EXESORT_display()
            case.CASERESULT = the_detail.get_CASERESULT_display()
        the_punish = ELCasePunish.objects.filter(caseid=case.caseid).first()
        if the_punish:
            case.ILLEGACTTYPE = the_punish.ILLEGACTTYPE
            case.PENDECISSDATE = the_punish.PENDECISSDATE
            case.PENAUTH = the_punish.PENAUTH
            case.PENDECNO = the_punish.PENDECNO
            case.ILLEGFACT = the_punish.ILLEGFACT
            case.PENBASIS = the_punish.PENBASIS
            case.PENTYPE = the_punish.get_PENTYPE_display()
            case.PENRESULT = the_punish.get_PENRESULT_display()
            case.PENAM = the_punish.PENAM
            case.PENEXEST = the_punish.PENEXEST
        if the_detail or the_punish:
            context["case_basic"].append(case)

    # 资产交易
    if version in ["10", ]:
        mort_objs = ELMortReg.objects.filter(entid_id=entid)
        if mort_objs.count():
            context["el_mort_guas"] = ELMortGua.objects.filter(MORREG_ID__in=[x.MORREG_ID for x in mort_objs])
        else:
            context["el_mort_guas"] = []
        for mort_obj in mort_objs:
            the_claim = mort_obj.mort_claim.all().first()
            if the_claim:
                mort_obj.the_claim = the_claim
            else:
                mort_obj.the_claim = ELMortClaim()
        context["el_morts"] = mort_objs
        # 专利信息
        context["el_patents"] = ELPatentEnt.objects.filter(entid_id=entid)

        # 商标
        el_tminfo = ELTminfo.objects.filter(entid_id=entid)
        context["el_tminfo_count"] = el_tminfo.count()
        context["el_tminfo"] = el_tminfo[:200]

        # 著作权
        context["zzq_objs"] = ELCopyrightSoftware.objects.filter(entid=entid)  # FBAPI(el_post.REGNO).get_zzq()

        # 电力模型数据
        try:
            electricity_data = getJsonData(company_obj.ENTNAME)
            if electricity_data is None or electricity_data == "":
                electricity_data = getJsonDetail()
        except TypeError as e:
            electricity_data = getJsonDetail()
        # electricity_data = getJsonDetail()
        context['data'] = electricity_data

    # 事件舆情
    # if version in ["10", ]:
    #     context["news_objs"] = []
    #     if len(el_post.REGNO) > 7:
    #         news_dict = FBAPI(el_post.REGNO).get_news()
    #         if "event" in news_dict and "total" in news_dict["event"] and "hits" in news_dict["event"]:
    #             news_dict = news_filter(news_dict)
    #             context["news_objs"] = news_dict["event"]["hits"]

    # 招标招聘
    # if version in ["10", ]:
    #     context["ztb_objs"] = []
    #     if len(el_post.REGNO) > 7:
    #         ztb_dict = FBAPI(el_post.REGNO).get_bid()
    #         if "total" in ztb_dict and "hits" in ztb_dict:
    #             ztb_objs = []
    #             key_dict = {"发布时间": "fbsj", "公告类型": "gglx", "地区": "dq", "标题": "bt", "正文": "zw", "采购人": "cgr",
    #                         "采购品目": "cgpm", "代理机构": "dljg"}
    #             for tmp in ztb_dict["hits"]:
    #                 new_obj = {"fbsj": "", "gglx": "", "dq": "", "bt": "", "zw": "", "cgr": "", "cgpm": "", "dljg": ""}
    #                 for key in key_dict.keys():
    #                     if key in tmp:
    #                         new_obj[key_dict[key]] = tmp[key]
    #                         ztb_objs.append(new_obj)
    #             context["ztb_objs"] = ztb_objs
    #     zp_objs = WmyAPI(el_post.ENTNAME).get_zp()
    #     for tmp in zp_objs:
    #         for ky in ["job_name", "posttime", "location", "education_requirement", "experience_requirement",
    #                    "salary_range", "url"]:
    #             if ky not in tmp:
    #                 tmp[ky] = ""
    #     context["zp_objs"] = zp_objs

    # 渲染模版
    context['today'] = datetime.today()
    t1 = get_template("element/reportpdf_for_java/index.html")
    context['path'] = 'http://' + request.get_host()
    c = RequestContext(request, context)
    html = t1.render(c)

    options = {
        'margin-right': '0',
        'margin-left': '0',
        'encoding': "UTF-8",
        'header-spacing': 20,
        'header-html': 'templates/element/reportpdf_for_java/header.html',
        'footer-center': "--  [page]  --",
        'margin-bottom': '10',
        'footer-spacing': 1,
        'footer-font-size': 12,
        'footer-html': 'templates/element/reportpdf_for_java/footer.html',
        'javascript-delay': 700,
        'page-offset': -1,
        'outline-depth': 2
    }
    cover = 'http://' + request.get_host() + request.path + 'cover/?version=%s' % version
    toc = {
        'xsl-style-sheet': 'static/element/reportpdf/toc.xml'
    }

    # 创建内容页
    pdf = pdfkit.from_string(str(html.encode('utf-8')).decode('utf-8'), False, options=options, toc=toc, cover=cover,
                             cover_first=True)

    # response = HttpResponse(mimetype='application/pdf')
    # response['Content-Disposition'] = (
    #     'filename=%s-征信企业报告(%s).pdf' % (el_post.ENTNAME, version_dict[version])).encode("utf-8")

    response = HttpResponse(mimetype='application/force-download')
    response['Content-Disposition'] = (
        'attachment;filename=%s-征信企业报告.pdf' % el_post.ENTNAME).encode("utf-8")
    response.write(pdf)
    return response


@never_cache
def pdf_cover_for_java(request, entid=None):
    entid = wldecode(entid, addcrc=True)
    if not entid or entid > 500000000:
        raise Http404
    el_post = get_object_or_404(ELPost, entid=entid)
    context = {"el_post": el_post, }
    context['path'] = 'http://' + request.get_host()
    context['today'] = datetime.today()
    context['version'] = request.GET['version'] or '11'
    return render(request, "element/reportpdf_for_java/cover.html", context)
